package com.breeze.queue;

/**
 * 队列
 * 链式结构
 * 队尾插入，队头获取
 */
public class LinkQueue<T> {
    Node<T> front, rear;
    int size;

    public LinkQueue() {
        front = rear = new Node(-1, null);
    }

    public void enqueue(T e) {
        rear = rear.next = new Node<>(e, null);
        size++;
    }

    public T dequeue() {
        if (front.next == null) {
            System.out.println("队列为空");
            return null;
        }
        size--;
        // 方法1
        /*Node<T> node = front.next;
        front.next = node.next;
        if (front.next == null) {
            rear = front;
        }
        return node.val;*/
        // 方法2，没发现问题，该种方式更简洁
        front = front.next;
        return front.val;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return front == rear;
    }

    public void clear() {
        front.next = null;
        rear = front;
    }


    static class Node<T> {
        T val;
        Node<T> next;

        public Node(T val, Node<T> next) {
            this.val = val;
            this.next = next;
        }
    }
}
